package com.tjec.project.projectLeaderWorkbeanch.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tjec.common.constant.Constants;
import com.tjec.common.constant.UserConstants;
import com.tjec.common.utils.DateUtils;
import com.tjec.common.utils.SecurityUtils;
import com.tjec.common.utils.ServletUtils;
import com.tjec.common.utils.StringUtils;
import com.tjec.common.utils.poi.ExcelUtil;
import com.tjec.framework.aspectj.lang.annotation.Log;
import com.tjec.framework.aspectj.lang.enums.BusinessType;
import com.tjec.framework.interceptor.annotation.RepeatSubmit;
import com.tjec.framework.security.service.TokenService;
import com.tjec.framework.web.controller.BaseController;
import com.tjec.framework.web.domain.AjaxResult;
import com.tjec.framework.web.page.TableDataInfo;
import com.tjec.project.mdmSynchronous.domain.MdmUser;
import com.tjec.project.mdmSynchronous.service.MdmUserService;
import com.tjec.project.portal.service.IBmsMsgService;
import com.tjec.project.projectLeaderWorkbeanch.domain.BmsLeaderMember;
import com.tjec.project.projectLeaderWorkbeanch.service.IBmsLeaderMemberService;
import com.tjec.project.projectWorkbench.domain.BmsProjectMember;
import com.tjec.project.projectWorkbench.service.IBmsProjectMemberService;
import com.tjec.project.projectWorkbench.service.IBmsProjectService;
import com.tjec.project.system.domain.SysUser;
import com.tjec.project.system.mapper.SysUserRoleMapper;
import com.tjec.project.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 项目负责人人员Controller
 *
 * @author tjec
 * @date 2020-04-14
 */
@Api(value = "项目负责人工作台-人员清单管理接口", tags = {"项目负责人工作台-人员清单管理接口"})
@RestController
@RequestMapping("/projectleader/personnel")
public class BmsLeaderMemberController extends BaseController {
    @Autowired
    private IBmsLeaderMemberService bmsLeaderMemberService;

    @Autowired
    private IBmsProjectMemberService bmsProjectMemberService;

    @Autowired
    private IBmsProjectService iBmsProjectService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private MdmUserService mdmUserService;

    @Autowired
    private IBmsMsgService bmsMsgService;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private TokenService tokenService;

    /**
     * 查询项目负责人人员列表
     */
    @ApiOperation("查询项目负责人人员列表")
//    @PreAuthorize("@ss.hasPermi('projectleader:personnel:list')")
    @GetMapping("/list")
    public TableDataInfo list(BmsLeaderMember bmsLeaderMember) {
        /*String projectLeaderNo = sysUserService.findProjectLeaderNoByUserGuid(bmsLeaderMember.getLeader());
        if(StringUtils.isNotBlank(projectLeaderNo)){
            bmsLeaderMember.setLeader(projectLeaderNo);
        }*/
        startPage();
        List<BmsLeaderMember> list = bmsLeaderMemberService.selectBmsLeaderMemberList(bmsLeaderMember);
        for (BmsLeaderMember leaderMember : list) {
            if(StringUtils.isNotBlank(leaderMember.getUserId())){
                Map<String, Object> map = iBmsProjectService.countMyProject(leaderMember.getUserId());
                if(null!=map&&map.size()>0){
                    leaderMember.setPreparationNo(Integer.valueOf(map.get("preparationNo").toString()));
                    leaderMember.setProcessingNo(Integer.valueOf(map.get("processingNo").toString()));
                    leaderMember.setDeliveryNo(Integer.valueOf(map.get("deliveryNo").toString()));
                    leaderMember.setTotalNo(Integer.valueOf(map.get("totalNo").toString()));
                }
            }
        }
        return getDataTable(list);
    }

    /**
     * 获取项目负责人人员详细信息
     */
    @ApiOperation("获取项目负责人人员详细信息")
    @ApiImplicitParam(name = "guid", value = "项目负责人人员guid", required = true, dataType = "String", paramType = "path")
//    @PreAuthorize("@ss.hasPermi('projectleader:personnel:query')")
    @GetMapping(value = "/{guid}")
    public AjaxResult getInfo(@PathVariable("guid") String guid) {
        return AjaxResult.success(bmsLeaderMemberService.selectBmsLeaderMemberByGuid(guid));
    }

    /**
     * 新增项目负责人人员
     */
    @ApiOperation("新增项目负责人人员")
    @ApiImplicitParam(name = "bmsLeaderMember", value = "新增项目负责人人员", dataType = "BmsLeaderMember")
    @Log(title = "项目负责人人员", businessType = BusinessType.INSERT)
//    @PreAuthorize("@ss.hasPermi('projectleader:personnel:add')")
    @RepeatSubmit
    @Transactional
    @PostMapping
    public AjaxResult add(@RequestBody BmsLeaderMember bmsLeaderMember)throws Exception {
        /*String projectLeaderNo = sysUserService.findProjectLeaderNoByUserGuid(bmsLeaderMember.getLeader());
        if(StringUtils.isNotBlank(projectLeaderNo)){
            bmsLeaderMember.setLeader(projectLeaderNo);
        }*/
        //用户不存在系统，新增用户
        if (StringUtils.isBlank(bmsLeaderMember.getUserId())) {
            String userId = insertUser(bmsLeaderMember);
            bmsLeaderMember.setUserId(userId);
        }
        boolean repeatFlag = bmsLeaderMemberService.repeatBmsLeaderMember(bmsLeaderMember.getLeader(), bmsLeaderMember.getUserId());
        if(repeatFlag){
            return AjaxResult.error("添加人员已存在");
        }
        bmsLeaderMember.setRole("0");
        if(bmsLeaderMember.getUserId()!=null){
            SysUser user = userService.selectUserById(bmsLeaderMember.getUserId());
            if (user.getStatus()!=null&&(user.getStatus().equals("2")||user.getStatus().equals("未启用"))) {
                Set<String> userIds = sysUserRoleMapper.selectUserIdByRoleKey(Constants.ROLE_SYSTEM_ADMINISTRATOR_KEY);
                if (!CollectionUtils.isEmpty(userIds)) {
                    for (String userId : userIds) {
                        String msgType = "申请开通账号";
                        String content = tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getNickName() +"：“姓名：" + user.getNickName() + "、员工编号：" + user.getJobNo() + "申请开通账号，请处理。”";
                        bmsMsgService.insertByReceiverUser(userId, msgType, content,true);
                    }
                }
            }
        }
        return toAjax(bmsLeaderMemberService.insertBmsLeaderMember(bmsLeaderMember));
    }

    private String insertUser(BmsLeaderMember bmsLeaderMember)throws Exception{
        SysUser sysUser = new SysUser();
        sysUser.setNickName(bmsLeaderMember.getNickName());
        sysUser.setJobNo(bmsLeaderMember.getJobNo());
        sysUser.setPhonenumber(bmsLeaderMember.getPhonenumber());
        sysUser.setStatus("2");
        sysUser.setGlobalId(bmsLeaderMember.getGlobalId());
        sysUser.setPersonnelDept(bmsLeaderMember.getPersonnelDept());
        sysUser.setBpmUserId(bmsLeaderMember.getBpmUserId());
        if (UserConstants.NOT_UNIQUE.equals(userService.checkJobNoUnique(sysUser))) {
            throw new Exception("新增用户失败，员工编号已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(sysUser))) {
            throw new Exception("新增用户失败，手机号码已存在");
        }
        sysUser.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId());
        sysUser.setPassword(SecurityUtils.encryptPassword(Constants.INITIAL_PASSWORD));
        userService.insertUserLeader(sysUser);
        return sysUser.getGuid();
    }

    /**
     * 删除项目负责人人员
     */
    @ApiOperation("删除项目负责人人员")
    @ApiImplicitParam(name = "guids", value = "项目负责人人员guid", required = true, dataType = "Array", paramType = "path")
    @Log(title = "删除项目负责人人员", businessType = BusinessType.DELETE)
//    @PreAuthorize("@ss.hasPermi('projectleader:personnel:remove')")
    @PostMapping("/delete")
    public AjaxResult remove(@RequestBody BmsLeaderMember bmsLeaderMember) throws Exception {
        /*String projectLeaderNo = sysUserService.findProjectLeaderNoByUserGuid(bmsLeaderMember.getLeader());
        if(StringUtils.isNotBlank(projectLeaderNo)){
            bmsLeaderMember.setLeader(projectLeaderNo);
        }*/
        return toAjax(bmsLeaderMemberService.deleteBmsLeaderMemberByGuids(bmsLeaderMember.getGuids(), bmsLeaderMember.getLeader()));
    }

    /**
     * 申请开通账号
     */
    @ApiOperation("申请开通账号")
    @PostMapping("/applyAccount/{guids}")
//    @PreAuthorize("@ss.hasPermi('project:member:applyAccount')")
    public AjaxResult applyAccount(@PathVariable("guids") String[] guids)throws Exception
    {
        List<BmsLeaderMember> list = new ArrayList<>();
        if(guids!=null&&guids.length>0){
            list = bmsLeaderMemberService.selectBmsLeaderMemberByGuids(guids);
        }
        applySendMsg(list);
        return AjaxResult.success();
    }

    /**
     * 申请开通账号
     */
    @ApiOperation("申请开通账号")
    @GetMapping("/applyAccount")
//    @PreAuthorize("@ss.hasPermi('project:member:applyAccount')")
    public AjaxResult applyAccount(BmsLeaderMember bmsLeaderMembers)throws Exception
    {
        List<BmsLeaderMember> list = new ArrayList<>();
        list.add(bmsLeaderMembers);
        applySendMsg(list);
        return AjaxResult.success();
    }

    private void applySendMsg(List<BmsLeaderMember> bmsLeaderMembers)throws Exception{
        Set<String> userIds = sysUserRoleMapper.selectUserIdByRoleKey(Constants.ROLE_SYSTEM_ADMINISTRATOR_KEY);
        for (BmsLeaderMember bmsLeaderMember : bmsLeaderMembers) {
            if (bmsLeaderMember.getStatus()!=null&&!(bmsLeaderMember.getStatus().equals("2")||bmsLeaderMember.getStatus().equals("未启用"))) {
                throw new Exception("申请用户'" + bmsLeaderMember.getNickName() + "'非未启用状态");
            }
            if (!CollectionUtils.isEmpty(userIds)) {
                for (String userId : userIds) {
                    String msgType = "申请开通账号";
                    String content = tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getNickName() +"：姓名：" + bmsLeaderMember.getNickName() + "、员工编号：" + bmsLeaderMember.getJobNo() + "申请开通账号，请处理。";
                    bmsMsgService.insertByReceiverUser(userId, msgType, content,true);
                }
            }
        }
    }

    /**
     * 查询添加人员页面人员列表
     */
    @ApiOperation("查询添加人员页面人员列表")
//    @PreAuthorize("@ss.hasPermi('projectleader:personnel:addMemberList')")
    @GetMapping("/addMemberList")
    public TableDataInfo memberList(BmsLeaderMember bmsLeaderMember) {
//        startPage();
        /*String projectLeaderNo = sysUserService.findProjectLeaderNoByUserGuid(bmsLeaderMember.getLeader());
        if(StringUtils.isNotBlank(projectLeaderNo)){
            bmsLeaderMember.setLeader(projectLeaderNo);
        }*/
        List<SysUser> list = bmsLeaderMemberService.selectSysUserList(bmsLeaderMember);
        if(CollectionUtils.isEmpty(list)){
            MdmUser mdmUser = new MdmUser();
            mdmUser.setUserName(bmsLeaderMember.getNickName());
            mdmUser.setJobNo(bmsLeaderMember.getJobNo());
            List<MdmUser> mdmUserlist =mdmUserService.selectMdmUserByName(mdmUser);
            ObjectMapper objectMapper =  new ObjectMapper();
            List<MdmUser> mdmUsers = objectMapper.convertValue(mdmUserlist, new TypeReference<List<MdmUser>>() { });
            if(!CollectionUtils.isEmpty(mdmUsers)){
                for (MdmUser user : mdmUsers) {
                    SysUser sysUser = new SysUser();
                    sysUser.setNickName(user.getUserName());
                    sysUser.setJobNo(user.getJobNo());
                    sysUser.setPhonenumber(user.getPhoneNumber());
                    sysUser.setStatus("2");
                    sysUser.setGlobalId(user.getGlobalId());
                    sysUser.setPersonnelDept(user.getPersonnelDept());
                    sysUser.setBpmUserId(user.getObjectID());
                    list.add(sysUser);
                }
            }
        }
        return getDataTable(list);
    }

    @GetMapping("/checkLeaderMember")
    public AjaxResult checkLeaderMember(BmsLeaderMember bmsLeaderMember) {
    	return AjaxResult.success(bmsLeaderMemberService.checkLeaderMember(bmsLeaderMember));
    }

    /**
     * 查询历史项目信息变更
     */
    @ApiOperation("查询历史项目信息变更")
//    @PreAuthorize("@ss.hasPermi('projectleader:personnel:historyProjectList')")
    @GetMapping("/historyProjectList")
    public TableDataInfo historyProjectList(BmsProjectMember bmsProjectMember) {
        startPage();
        List<BmsProjectMember> list = bmsProjectMemberService.selectHistoryProjectList(bmsProjectMember);
        for (BmsProjectMember projectMember : list) {
            BmsProjectMember pm = new BmsProjectMember();
            pm.setProjectId(projectMember.getProjectId());
            pm.setUserId(projectMember.getUserId());
            pm.setDelFlag("0");
            List<BmsProjectMember> bmsProjectMemberList = bmsProjectMemberService.selectBmsProjectMemberList(pm);
            if(!CollectionUtils.isEmpty(bmsProjectMemberList)){
                projectMember.setProjectMemberFlag("Y");
            }else{
                projectMember.setProjectMemberFlag("N");
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出历史项目信息
     */
    @ApiOperation("导出历史项目信息")
//    @PreAuthorize("@ss.hasPermi('projectleader:personnel:exportHistory')")
    @Log(title = "项目负责人人员", businessType = BusinessType.EXPORT)
    @GetMapping("/exportHistory")
    public AjaxResult export(BmsProjectMember bmsProjectMember) {
        List<BmsProjectMember> list = bmsProjectMemberService.selectHistoryProjectList(bmsProjectMember);
        for (BmsProjectMember projectMember : list) {
            if(StringUtils.isBlank(projectMember.getProjectStatus())){
                projectMember.setProjectStatus("");
            }else {
                if (projectMember.getProjectStatus().equals("0")) {
                    projectMember.setProjectStatus("筹备");
                } else if (projectMember.getProjectStatus().equals("1")) {
                    projectMember.setProjectStatus("进行中");
                } else if (projectMember.getProjectStatus().equals("2")) {
                    projectMember.setProjectStatus("成果交付");
                } else if (projectMember.getProjectStatus().equals("3")) {
                    projectMember.setProjectStatus("项目完成");
                } else if (projectMember.getProjectStatus().equals("4")) {
                    projectMember.setProjectStatus("项目暂停");
                } else if (projectMember.getProjectStatus().equals("5")) {
                    projectMember.setProjectStatus("项目终止");
                } else if (projectMember.getProjectStatus().equals("6")) {
                    projectMember.setProjectStatus("项目作废");
                }
            }
            if (projectMember.getProjectMemberFlag().equals("Y")) {
                projectMember.setProjectMemberFlag("是");
            } else {
                projectMember.setProjectMemberFlag("否");
            }
        }
        ExcelUtil<BmsProjectMember> util = new ExcelUtil<>(BmsProjectMember.class);
        return util.exportExcelMergeSameColumn(list, "projectHistory", getMergedRegionIndexs(list, 4));
    }

    /**
     * 根据数据获取需要合并的单元格的集合
     * @param list
     * @param mergeCols
     * @return
     */
    private List<String> getMergedRegionIndexs(List<BmsProjectMember> list,int mergeCols){
        List<String> mergedRegionIndexs  = new ArrayList<>();
        if(!CollectionUtils.isEmpty(list)){
            int startRow = 0;
            for (int i = 0; i < list.size(); i++) {
                if(i==0){
                    continue;
                }
                if((list.get(i).getProjectId()).equals(list.get(i-1).getProjectId())){
                    startRow++;
                }else{
                    if(startRow>0){
                        for (int j = 0; j < mergeCols; j++) {
                            mergedRegionIndexs.add(i-startRow+";"+i+";"+j+";"+j+";");
                        }
                        startRow =0;
                    }
                }
            }
            if(startRow>0){
                for (int j = 0; j < mergeCols; j++) {
                    mergedRegionIndexs.add(list.size()-startRow+";"+list.size()+";"+j+";"+j+";");
                }
            }
        }
        return mergedRegionIndexs;
    }
}
